package com.ly.juc;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname MapUnsafe
 * @Description TODO
 * @Date 2020/10/4 15:35
 * @Author 冷心影翼
 */
public class MapUnsafe {

	public static void main(String[] args) {
//		unsafe();
		collectionsSynchronizedMap();
		concurrentHashMap();
	}

	public static void unsafe() {
		Map map = new HashMap();
		for(int i=0;i<100;i++) {
			int finalI = i;
			new Thread(()->{
				map.put(finalI,"A");
				System.out.println(map);
			}).start();
		}
	}

	public static void collectionsSynchronizedMap() {
		Map<Object, Object> map = Collections.synchronizedMap(new HashMap<>());
		for(int i=0;i<100;i++) {
			int finalI = i;
			new Thread(()->{
				map.put(finalI,"A");
				System.out.println(map);
			}).start();
		}
	}

	public static void concurrentHashMap() {
		Map<Object, Object> map = new ConcurrentHashMap<>();
		for(int i=0;i<100;i++) {
			int finalI = i;
			new Thread(()->{
				map.put(finalI,"A");
				System.out.println(map);
			}).start();
		}
	}
}
